package com.wizz.trade.trading.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wizz.trade.common.PageVo;
import com.wizz.trade.common.ServiceException;
import com.wizz.trade.information.mapper.CompanyMapper;
import com.wizz.trade.information.mapper.CompanydeptMapper;
import com.wizz.trade.information.mapper.CurrencyMapper;
import com.wizz.trade.trading.dto.ConsDto;
import com.wizz.trade.trading.dto.page.ConsPageDto;
import com.wizz.trade.trading.entity.Cons;
import com.wizz.trade.trading.entity.Trade;
import com.wizz.trade.trading.mapper.ConsMapper;
import com.wizz.trade.trading.mapper.TradeMapper;
import com.wizz.trade.trading.service.ConsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wizz.trade.trading.vo.ConsVo;
import com.wizz.trade.util.FileOperationUtil;
import com.wizz.trade.util.PageUtil;
import com.wizz.trade.util.SeqIdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 合同表 服务实现类
 * </p>
 *
 * @author fyftless
 * @since 2023-04-23 04:37:04
 */
@Service
public class ConsServiceImpl extends ServiceImpl<ConsMapper, Cons> implements ConsService {

    @Resource
    private ConsMapper consMapper;

    @Resource
    private SeqIdGenerator seqIdGenerator;

    @Resource
    private TradeMapper tradeMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private CompanydeptMapper companydeptMapper;

    @Resource
    private CurrencyMapper currencyMapper;

    @Resource
    private FileOperationUtil fileOperationUtil;

    @Override
    public void addCons(ConsDto consDto) {
        //最大贸易记录数量
        final int maxTradeNum = 5;
        //TODO 不知道印花税率多少，这里暂定为0.01
        //默认印花税率
        final BigDecimal taxRate = BigDecimal.valueOf(0.01);

        //数据校验
        List<Integer> ids = consDto.getTradeIds();
        if(ids.size() == 0 || ids.size() > maxTradeNum){
            throw new ServiceException("关联合同数量不得超过5");
        }
        //获取贸易记录
        List<Trade> trades = tradeMapper.selectBatchIds(ids);
        Cons cons = new Cons();
        //取第一项作为公共关联字段
        Trade firstTrade = trades.get(0);
        //1.计算合同金额
        BigDecimal consPrice = BigDecimal.valueOf(0);
        for (Trade trade : trades) {
            consPrice = consPrice.add(trade.getAmount());
        }
        cons.setConamt(consPrice);
        //2.获取关联字段
        cons.setLedger(firstTrade.getLedgerId());
        cons.setOurDept(firstTrade.getOurDeptId());
        cons.setPs(firstTrade.getPs());
        cons.setCurrency(firstTrade.getCurrencyId());
        //3.设置日期
        cons.setDate(consDto.getDate());
        //4.生成合同编号
        StringBuilder sb = new StringBuilder();
        sb.append(firstTrade.getPs());
        sb.append(firstTrade.getLedgerId());
        sb.append(firstTrade.getOurDeptId());
        sb.append(cons.getDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        String prefix = sb.toString();
        cons.setContractno(prefix + seqIdGenerator.generateAutoIncreaseSeqId(prefix, 3));
        //5.其余字段填充
        cons.setNote(consDto.getNote());
        cons.setActsd(consDto.getActsd());
        cons.setSd(cons.getConamt().multiply(taxRate));
        consMapper.insert(cons);
    }

    @Override
    public void updateCons(Cons cons) {
        consMapper.updateById(cons);
    }

    @Override
    public void deleteCons(Integer id) {
        consMapper.deleteById(id);
    }

    @Override
    public PageVo<ConsVo> getPage(ConsPageDto consPageDto) {
        IPage<Cons> page = consMapper.getPage(PageUtil.initPage(consPageDto), consPageDto);
        List<Cons> records = page.getRecords();
        List<ConsVo> result = new ArrayList<>();
        for (Cons record : records) {
            ConsVo consVo = new ConsVo();
            BeanUtils.copyProperties(record, consVo);
            consVo.setLedger(companyMapper.selectById(record.getLedger()).getShortname());
            consVo.setOurDept(companydeptMapper.selectById(record.getOurDept()).getName());
            consVo.setCurrency(currencyMapper.selectById(record.getCurrency()).getName());
            result.add(consVo);
        }
        return new PageVo<>(page.getPages(), page.getTotal(), result);
    }

    @Override
    public List<Cons> getAll() {
        return consMapper.selectList(null);
    }

    @Override
    public void contractFiling(List<Integer> consIds) {
        consMapper.contractFiling(consIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadConsImage(Integer consId, MultipartFile multipartFile) {
        String url = fileOperationUtil.uploadImage(multipartFile);
        Cons cons = consMapper.selectById(consId);
        cons.setScan(url);
        consMapper.updateById(cons);
        return url;
    }
}
